package reviewAlgorithms.ListNode;

import java.util.Stack;

public class AddTwoNumbers {
    public static void main(String[] args) {

    }
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null || l2 == null){
            return null;
        }
        Stack<ListNode> stackList1 = new Stack<>();
        Stack<ListNode> stackList2 = new Stack<>();
        while (l1 != null){
            stackList1.push(l1);
            l1= l1.next;
        }
        while (l2 != null){
            stackList2.push(l2);
            l2 = l2.next;
        }
        int up = 0;
        ListNode res = null;
        Stack<ListNode> retain;
        while (!stackList1.empty() && !stackList2.empty()){
            ListNode listNode1 = stackList1.pop();
            ListNode listNode2 = stackList2.pop();
            if (listNode1.val  + listNode2.val + up < 10){
                ListNode temp = new ListNode(listNode1.val  + listNode2.val + up);
                temp.next = res;
                res = temp;
                up = 0;
            }else {
                ListNode temp = new ListNode(listNode1.val  + listNode2.val + up - 10);
                temp.next = res;
                res = temp;
                up = 1;
            }
        }
        if (!stackList1.empty()){
            retain = stackList1;
        }else {
            retain = stackList2;
        }
        while (!retain.empty()){
            ListNode nodeRetain = retain.pop();
            if (nodeRetain.val + up < 10){
                ListNode temp = new ListNode(nodeRetain.val + up);
                temp.next = res;
                res = temp;
                up = 0;
            }else {
                ListNode temp = new ListNode(nodeRetain.val + up - 10);
                temp.next = res;
                res = temp;
                up = 1;
            }
        }
        if (up == 1){
            ListNode temp = new ListNode(up);
            temp.next = res;
            res = temp;
            return res;
        }
        return res;
    }
}
